<template>
	<el-dialog title="兑换商品设置" :visible.sync="isShow" :close-on-click-modal="false" :before-close="close" width="800px">
		<div class="form-box">
			<el-form ref="form" :model="form" :rules="rules" label-width="110px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="商品图片">
							<el-image class="pic" fit="cover" :src="item.skuThumbImage" :preview-src-list="[item.skuThumbImage]"></el-image>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="24">
						<el-form-item label="商品名称">
							<el-input v-model="item.productName" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="SKU名称">
							<el-input v-model="item.skuName" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="当前库存数量">
							<el-input v-model="item.stock" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="24">
						<el-form-item label="兑换用券数量" prop="couponQuantity">
							<el-input v-model="form.couponQuantity" placeholder="请填写兑换需要的券数量" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		
		<div slot="footer">
			<el-button type="primary" @click="submit">保 存</el-button>
			<el-button @click="close">取 消</el-button>
		</div>
	</el-dialog>
</template>

<script>
	import { addExchangeProduct } from '@api/product/productSkuSale'
	export default {
		props: {
			isShow: Boolean,
			item: Object,
		},
		data() {
			let validateCouponQuantity = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请填写兑换需要的券数量'));
				} else if(!/^\d*\.?\d*$/.test(Math.abs(value))) {
					callback(new Error('用券数量只能输入数字'));
				} else if(parseFloat(value) <= 0) {
					callback(new Error('用券数量必须大于0'));
				} else {
					callback();
				}
			}
			return {
				form: {
					couponQuantity: '',
				},
				rules: {
					couponQuantity: [{ required: true, validator: validateCouponQuantity, trigger: 'blur' }],
				},
			}
		},
		methods: {
			submit() {
				this.$refs.form.validate(valid => {
					if (valid) {
						let params = {
							skuSaleId: this.item.id,
							couponQuantity: parseFloat(this.form.couponQuantity),
							exchangeStatus: 1,
						}
						addExchangeProduct(params)
							.then(() => {
								this.$message.success('兑换商品设置成功！');
								this.close();
							})
					}
				})
			},
			
			reset() {
				this.$refs.form.resetFields();
			},
			close() {
				this.$emit('close');
				this.reset();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20px;
	}
	
	.pic {
		width: 100px;
		height: 100px;
	}
</style>